/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * @author yaoyuming
 * @date  2020/8/28 0028
 */
package com.yao.security.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class SuccessHandler implements AuthenticationSuccessHandler {

      private RequestCache requestCache = new HttpSessionRequestCache();
      private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

      @Override
      public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            log.info("打印登陆信息:{}",authentication);

            // 跳转访问页面
            SavedRequest savedRequest = requestCache.getRequest(request, response);
            log.info("跳转访问页面:{}", savedRequest.getRedirectUrl());

            redirectStrategy.sendRedirect(request, response, savedRequest.getRedirectUrl());
            // todo 实际上应该跳转到主页，而不是最初访问的.html后缀的地址，不然就可以绕过主页去到其他界面，这样是不符合实际业务的
      }
}